package com.bw.house.config;

import com.alibaba.fastjson.JSON;
import com.bw.house.entity.HouseRentEntity;
import com.bw.house.service.HouseRentService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author jwcz
 * @Date 2022/3/27 20:44
 * @Version 1.0
 */
@Component
public class MyRunner implements ApplicationRunner {

    @SuppressWarnings("all")
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private HouseRentService houseRentService;


    @Override
    public void run(ApplicationArguments args) throws Exception {

        List<HouseRentEntity> houseEntityList = houseRentService.list();
        BulkRequest bulkRequest = new BulkRequest();
        for (HouseRentEntity entity : houseEntityList) {
            IndexRequest request = new IndexRequest("house");
            request.id(entity.getHouseId()+"");
            String jsonString = JSON.toJSONString(entity);
            request.source(jsonString, XContentType.JSON);

            bulkRequest.add(request);
        }
        System.out.println("项目已启动，数据已同步");
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
